<template>
  <div class="container">
    <div id="mars3dcontent"></div>
    <div class="layercontrol">
      <div class="item" style="display: flex">
        <div style="padding: 1vh">卫星地图</div>
        <el-switch
          style="padding: 1vh"
          size="large"
          v-model="imagemap"
          @change="switchImageLayer"
        />
      </div>
      <div class="item" style="display: flex">
        <div style="padding: 1vh">管网矢量地图</div>
        <el-switch
          style="padding: 1vh"
          size="large"
          v-model="pipemap"
          @change="switchPipLine"
        />
      </div>
    </div>
    <div class="tablecontainer" v-if="panelshow">
      <div class="tableForm">
        <div class="form">
          <div class="select">
            <div style="margin-left: 20px">流域：</div>
            <el-select
              v-model="basinvalue"
              placeholder="请选择..."
              size="large"
              style="width: 160px"
              @change="basinChange"
            >
              <el-option
                v-for="item in basinoptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
            <div>街道名称：</div>
            <el-input
              v-model="streetname"
              style="width: 160px"
              size="large"
              placeholder="请输入"
              @change="streetChange"
            />
            <div>道路名称：</div>
            <el-input
              v-model="roadname"
              style="width: 160px"
              size="large"
              placeholder="请输入"
              @change="roadChange"
            />
            <div>运行情况：</div>
            <el-select
              v-model="runtype"
              placeholder="请选择..."
              size="large"
              style="width: 160px"
              @change="runtypeChange"
            >
              <el-option
                v-for="item in runoptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </div>
          <div class="bottomlist">
            <el-button
              color="#0000ff"
              style="margin-left: 12px"
              :bg="false"
              size="large"
              plain
              @click="clearSearch"
              >清空</el-button
            >
            <el-button color="#0000ff" size="large" @click="searchTable">查询</el-button>
            <div class="div-button" style="margin-left: 35px" @click="closePanel">
              <img :src="close" />
            </div>
          </div>
        </div>
        <div class="tableposition">
          <el-table
            :data="tableData"
            :cell-style="cellgradeStyle"
            :header-cell-style="headerStyle"
            style="width: 97%"
            @row-dblclick="selectRow"
          >
            <el-table-column property="basin" label="流域名称" width="120" />
            <el-table-column property="streetName" label="街道名称" />
            <el-table-column property="roadName" label="道路名称" />
            <el-table-column property="componentName" label="部件名称" />
            <el-table-column property="componentNo" label="部件编号" />
            <el-table-column property="defectName" label="运营情况" />
            <el-table-column property="patrolTime" label="巡查时间" />
            <el-table-column property="gradeName" label="紧急程度"> </el-table-column>
          </el-table>
          <div class="page">
            <div>
              <span style="font-size: 16px">显示{{ pagerow }}条消息 </span>
              <el-input-number
                v-model="currentPage"
                :min="1"
                :max="100"
                controls-position="right"
              />
              <span style="font-size: 16px">
                共 <span style="color: blue">{{ pagenumber }}</span> 条消息</span
              >
            </div>
            <el-pagination
              layout="prev, pager, next"
              :total="pagenumber"
              :page-size="pagerow"
              v-model:current-page="currentPage"
              :change="changePage(value)"
            />
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import "mars3d-cesium/Build/Cesium/Widgets/widgets.css"; //依赖的cesium库本身css
import "mars3d/dist/mars3d.css";
import * as mars3d from "mars3d";
import { nextTick, onMounted, onUnmounted, reactive, watch } from "vue";
import { mapOptions } from "@/utils/mapOptions";
import { destroyMap, flytoView, transform, LayerCreate, AddGraphic } from "@/utils/Lmap";
import { operationDataAnalysis } from "@/api/dataAnalysis/dataAnalysis";
import useAppStore from "@/store/modules/app";

import close from "@/assets/trans/close.png";
import linestyle from "@/assets/trans/line-sprite.png";
import { Coordinate } from "@element-plus/icons-vue";

let map;
let imagemap = ref(false); // 影像地图
let pipemap = ref(false); // 管线地图

let panelshow = ref(true);

let basinoptions = [
  {
    value: "1",
    label: "跳墩河流域",
  },
  {
    value: "2",
    label: "肖家河流域",
  },
];

let runoptions = [
  {
    value: 1,
    label: "正常",
  },
  {
    value: 2,
    label: "异常",
  },
];

let runtype = ref(""); // 运维情况绑定值
let basinvalue = ref(""); // 流域绑定值
let streetname = ref(""); // 街道绑定值
let roadname = ref(""); // 道路绑定值

let searchform = reactive({
  basin: basinvalue.value,
  runInfo: runtype.value,
  roadName: roadname.value,
  streetName: streetname.value,
});

let totalData = [];
let tableData = ref([]);

let pagerow = ref(4); // 列表显示行
let pagenumber = ref(0); // 行的总数量
let currentPage = ref(1); // 当前页数

let layerline = new mars3d.layer.GraphicLayer({ zIndex: 1 }); // 显示线的图层
let layercluster = LayerCreate.createGraphicLayer(); // 聚类图层
let selectLayer = new mars3d.layer.GraphicLayer()

// 线数据
let pipline = [];

const LineSpriteType = "LineSprite";
mars3d.MaterialUtil.register(LineSpriteType, {
  fabric: {
    uniforms: {
      image: Cesium.Material.DefaultImageId,
      speed: 20,
      globalAlpha: 1.0,
    },
    source: `czm_material czm_getMaterial(czm_materialInput materialInput)
      {
        czm_material material = czm_getDefaultMaterial(materialInput);
        vec2 st = materialInput.st;
        vec4 colorImage = texture(image, vec2(fract(st.s - speed*czm_frameNumber/1000.0), st.t));
        material.alpha = colorImage.a * globalAlpha;
        material.diffuse = colorImage.rgb * 1.5 ;
        return material;
      }`,
  },
  translucent: true,
});

let tileLayer = new mars3d.layer.ArcGisLayer({
  url: "https://services.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer",
  enablePickFeatures: false,
});

const config = {
  url: "https://www.cqkckc.com/geoserver/hhgw/wms",
  layers: "hhgw:pipe_line",
  parameters: {
    VERSION: "1.1.1",
    transparent: true,
    format: "image/png",
  },
  crs: "EPSG:4326",
};
let wmsLayer = new mars3d.layer.WmsLayer(config);

const store = useAppStore();

watch(currentPage, (newval, oldval) => {
  tableData.value = JSON.parse(
    JSON.stringify(totalData.slice((newval - 1) * 4, (newval - 1) * 4 + 4))
  );
});

// 流域选择变化
function basinChange(value) {
  const select = basinoptions.find((item) => {
    if (item.value == value) {
      searchform.basin = item.label;
    }
  });
}

function runtypeChange(value) {
  searchform.runInfo = value;
}

// 清空按钮
function clearSearch() {
  layercluster.clear(true);
  layerline.clear(true);
  pipline.length = 0;
  searchform.basin = "";
  searchform.runInfo = "";
  runtype.value = "";
  basinvalue.value = "";
  streetname.value = "";
  roadname.value = "";
  totalData = [];
  getList();
}

// 管线
function addDemoGraphic11(position, info) {
  const graphic = new mars3d.graphic.PolylinePrimitive({
    positions: position,
    style: {
      width: 2.7,
      // 使用自定义材质
      materialType: LineSpriteType,
      materialOptions: {
        image: linestyle,
        speed: 10,
      },
    },
    attr: info,
  });
  layerline.addGraphic(graphic);
  return graphic;
}

function searchTable() {
  layercluster.clear(true);
  layerline.clear(true);
  pipline.length = 0;
  operationDataAnalysis(searchform).then((res) => {
    console.log(res);
    if (res.code == 200) {
      pagenumber.value = res.data.list.rows.length;
      totalData.length = 0;

      for (const eachdata of res.data.list.rows) {
        totalData.push(eachdata);
      }
      tableData.value = JSON.parse(JSON.stringify(totalData.slice(0, pagerow.value)));
      for (const eachdatainfo of res.data.point.features) {
        let line = {};
        let attr = eachdatainfo.properties;
        let eachgeometry = eachdatainfo.geometry;
        line.positions = eachgeometry.coordinates;
        line.attribute = attr;
        pipline.push(line);
      }
      createLine(); //添加
    }
  });
}

function createLine() {
  for (const eachpipe of pipline) {
    const inthtml = `<table style="width: auto;color:black;border-radius: 5px;">
    <tr>
      <th scope="col" colspan="2" style="text-align:center;font-size:15px;background-color:#EDF4FF">信息</th>
    </tr>
    <tr>
      <td>部件ID：</td>
      <td>${eachpipe.attribute.componentNo}</td>
    </tr>
    <tr>
      <td>部件类型：</td>
      <td>${eachpipe.attribute.componentName}</td>
    </tr>
  </table>`;
    let transformposition = [];
    for (const position of eachpipe.positions) {
      transformposition.push(transform(position));
    }
    let linegraphic = addDemoGraphic11(transformposition, eachpipe.attribute);
    let pointgraphic = AddGraphic.addDemoGraphic1(layercluster, transformposition[0]);
    linegraphic.bindPopup(inthtml);
    pointgraphic.bindPopup(inthtml);
  }
}

function searchPipline(name){
  for (const eachline of pipline) {
    if(eachline.attribute.componentNo == name){
      return eachline.positions[0];
    }
  }
}

// 添加四棱锥
function addTetrahedron(position) {
  let [lng,lat] = position;
  const tetrahedronPrimitive = new mars3d.graphic.Tetrahedron({
    position: Cesium.Cartesian3.fromDegrees(lng, lat, 0),
    style: {
      width: 20,
      height: 30,
      color: new Cesium.Color(0.8, 0.8, 0, 0.8),
      moveHeight: 40
    },
  })
  selectLayer.addGraphic(tetrahedronPrimitive)
}

// 点击列表查看地图位置
// center: { lat: 31.628661, lng: 117.251952, alt: 46390, heading: 2, pitch: -68,roll:}
function selectRow(row){
  let coordinates = searchPipline(row.componentNo);
  let [lng,lat] = transform(coordinates);
  let center = { lat:lat, lng: lng, alt: 100, heading: 0, pitch: -90,roll:0};
  console.log(lng,lat);
  flytoView(map,center);
  addTetrahedron(coordinates);
  setTimeout(()=>{
    selectLayer.clear(true);
  },10000)
}


// 获取列表
async function getList() {
  await operationDataAnalysis(searchform).then((res) => {
    console.log(res);
    pagenumber.value = res.data.list.rows.length;
    for (const eachdata of res.data.list.rows) {
      totalData.push(eachdata);
    }
    tableData.value = JSON.parse(JSON.stringify(totalData.slice(0, pagerow.value)));
    for (const eachdatainfo of res.data.point.features) {
      let line = {};
      let attr = eachdatainfo.properties;
      let eachgeometry = eachdatainfo.geometry;
      line.positions = eachgeometry.coordinates;
      line.attribute = attr;
      pipline.push(line);
    }
    createLine(); //添加
  });
}

// 设置表格的表头
function headerStyle({ row, column, rowIndex, columnIndex }) {
  return { color: "white", background: "#2A68F2" };
}

// 设置table单元格样式
function cellgradeStyle({ row, columnIndex }) {
  if (row.gradeName == "紧急" && columnIndex == 8) {
    return { color: "red" };
  }
  if (row.gradeName == "高" && columnIndex == 8) {
    return { color: "#DD966D" };
  }
  if (row.gradeName == "中" && columnIndex == 8) {
    return { color: "blue" };
  }
  if (row.gradeName == "低" && columnIndex == 8) {
    return { color: "green" };
  }
}

function changePage() {
  console.log(currentPage.value);
}

function switchImageLayer() {
  if (imagemap.value) {
    map.addLayer(tileLayer);
  } else {
    map.removeLayer(tileLayer);
  }
}

function switchPipLine() {
  if (pipemap.value) {
    map.addLayer(wmsLayer);
  } else {
    map.removeLayer(wmsLayer);
  }
}

// 关闭主页面表单
function closePanel() {
  panelshow.value = false;
}

const sideClick = (data) => {
  if (data.index == "/dataAnalysis/pipeAnalysis") panelshow.value = true;
};
store.changeSide(sideClick);

getList();

onMounted(async () => {
  map = new mars3d.Map("mars3dcontent", mapOptions);
  map.addLayer(layerline);
  map.addLayer(layercluster);
  map.addLayer(selectLayer);
});

onUnmounted(() => {
  destroyMap(map);
});
</script>

<style scoped>
.container {
  width: 100%;
  height: 100%;
  background-color: antiquewhite;
}

#mars3dcontent {
  width: 100%;
  height: 100%;
}

.layercontrol {
  position: fixed;
  top: 10vh;
  right: 10vh;
  width: 20vh;
  height: 10vh;
  border-radius: 1vh;
  background-color: white;
  z-index: 99;
  display: flex;
  flex-direction: column;
  justify-content: space-evenly;
  align-items: flex-start;
}

.item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  width: 100%;
}
.tablecontainer {
  position: absolute;
  display: flex;
  justify-content: center;
  align-items: center;
  bottom: 0px;
  width: 100%;
  height: 40%;
  z-index: 99;
}

.el-input-number {
  width: 70px;
  text-align: left;
}

.el-input-number :deep(.el-input__wrapper) {
  padding-right: 0px;
  padding-left: 0px;
}

.el-input-number :deep(.el-input__inner) {
  text-align: left;
  text-indent: 5px;
}

.tableForm {
  width: 90%;
  height: 95%;
  background-color: white;
  border-radius: 1vh;
  z-index: 99;
}

.form {
  margin-top: 20px;
  display: flex;
  height: 10%;
}

.tableposition {
  margin-top: 30px;
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100%;
  flex-direction: column;
}

.page {
  margin-top: 15px;
  width: 100%;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0px 30px;
}
.select {
  display: flex;
  width: 70%;
  flex-wrap: nowrap;
  justify-content: space-evenly;
  align-items: center;
}

.bottomlist {
  display: flex;
  width: 30%;
  flex-wrap: nowrap;
  justify-content: space-evenly;
  align-items: center;
}

/* Pop关闭按钮 */
.container :deep(.closeButton) {
  color: black;
}
.container :deep(.mars3d-popup-content) {
  margin: 0px;
  border-radius: 5px;
}
.container :deep(.mars3d-popup-background) {
  border-radius: 10px;
}

.el-table th {
  background-color: antiquewhite;
}

.el-dropdown-item {
  display: flex;
}
.div-button {
  cursor: pointer;
}
.el-button {
  width: 100px;
}
</style>
